package com.cnswhy.cloud.security.starter.configure;

import com.cnswhy.cloud.common.core.entity.constant.CnswhyConstant;
import com.cnswhy.cloud.common.core.utils.CnswhyUtil;
import com.cnswhy.cloud.security.starter.handler.CnswhyAccessDeniedHandler;
import com.cnswhy.cloud.security.starter.handler.CnswhyAuthExceptionEntryPoint;
import com.cnswhy.cloud.security.starter.properties.CnswhyGatewayProperties;
import feign.RequestInterceptor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.Base64Utils;

/**
 * @author cnswhy
 */
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableConfigurationProperties(CnswhyGatewayProperties.class)
@ConditionalOnProperty(value = "febs.cloud.security.enable", havingValue = "true", matchIfMissing = true)
public class CnswhyCloudSecurityAutoConfigure {

    @Bean
    @ConditionalOnMissingBean(name = "accessDeniedHandler")
    public CnswhyAccessDeniedHandler accessDeniedHandler() {
        return new CnswhyAccessDeniedHandler();
    }

    @Bean
    @ConditionalOnMissingBean(name = "authenticationEntryPoint")
    public CnswhyAuthExceptionEntryPoint authenticationEntryPoint() {
        return new CnswhyAuthExceptionEntryPoint();
    }

    @Bean
    @ConditionalOnMissingBean(value = PasswordEncoder.class)
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public CnswhyCloudSecurityInteceptorConfigure febsCloudSecurityInteceptorConfigure() {
        return new CnswhyCloudSecurityInteceptorConfigure();
    }

    @Bean
    public RequestInterceptor oauth2FeignRequestInterceptor() {
        return requestTemplate -> {
            String gatewayToken = new String(Base64Utils.encode(CnswhyConstant.GATEWAY_TOKEN_VALUE.getBytes()));
            requestTemplate.header(CnswhyConstant.GATEWAY_TOKEN_HEADER, gatewayToken);
            String authorizationToken = CnswhyUtil.getCurrentTokenValue();
            if (StringUtils.isNotBlank(authorizationToken)) {
                requestTemplate.header(HttpHeaders.AUTHORIZATION, CnswhyConstant.OAUTH2_TOKEN_TYPE + authorizationToken);
            }
        };
    }
}
